import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
  getGigaProductBaseInfo,
  getGigaSkuAndProductId,
  getProductPrice,
  getProductTotalPrice,
  gotoGigaProductPage,
} from '@/lib/giga';
import { cn, getOperationResultColor } from '@/lib/utils';
import {
  ColumnDef,
  ColumnPinningState,
  flexRender,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  PaginationState,
  SortingState,
  useReactTable,
} from '@tanstack/react-table';
import { ArrowUpDown, Search } from 'lucide-react';

import {
  getTemuUserInfo,
  queryBtgProductStockInfo,
  updateMmsBtgProductSalesStock,
} from '@/api/temu';
import TablePagination from '@/components/TablePagination';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import config, { PostMessageType, SendCorssOriginDataMessage } from '@/config';
import { getTemuTotalProductByMallId, getTemuTotalProductByProductIds } from '@/lib/temu';
import { useTemuNotPersisAvaliableSynchronizationStore } from '@/store/temuNotPersistAvaliableSynchronization';
import { memo, useDeferredValue, useId } from 'react';
import { toast } from 'sonner';
import useLocalStorage from '../hook/useLocalStorage';
import { AvaliableSynchronizationOperation } from './AvaliableSynchronizationOperation';
import { useFilterTable } from './hook/useFilterTable';
import { useSaveTableData } from './hook/useSaveTableData';

export interface AvaliableSynchronizationTableDataItem {
  skuInfo: string;
  temuStock: number;
  nextStock: number;
  gigaPrice: number;
  temuPrice: number;
  rateOfMargin: number;
  productId: number;
  skcId: number;
  skcInfo: string;
  skuId: number;
  mallId: number;
  productCreateAt: number;
  timeStamp: number;
  opeartionResult: string;
  gigaAvaliable: number;
  non_sellable_platform: string[];
}

export interface malInfo {
  mallId: number;
  mallName: string;
}

export interface SiteInfo {
  siteName: string;
  siteId: number;
}

export interface LocalStoredValue {
  mallId: number;
  siteId: number;
  status: number;
  fetchPageSize: number;
  synchronizationToZeroCondition: {
    // 最少货盘库存数
    minGigaAvaliable: number;
    // 毛利率 %((申报价 - giga 产品价格) / (giga 产品价格))
    minAndEqualRateOfMargin: number;
  };
}

export interface SkcTopStatus {
  label: string;
  status: number;
}

export interface RunTaskOptions {
  forceGigaAvaliable: number;
}

const siteList: SiteInfo[] = [
  {
    siteName: '美国站',
    siteId: 100,
  },
  {
    siteName: '欧洲站',
    siteId: 101,
  },
  {
    siteName: '其他站',
    siteId: 102,
  },
];

// 在售信息
const skcTopStatusList: SkcTopStatus[] = [
  {
    label: '全部',
    status: 1000,
  },
  {
    label: '在售中',
    status: 100,
  },
  {
    label: '未发布到站点',
    status: 0,
  },
  {
    label: '已下架/已终止',
    status: 200,
  },
];

function generateMallTableDataKey(storedValue: LocalStoredValue) {
  return `${storedValue.mallId}-${storedValue.siteId}-${storedValue.status}`;
}
export default function AvaliableSynchronization({
  className,
  ...props
}: {
  className: string;
} & React.HTMLAttributes<HTMLDivElement>) {
  const [tableData, setTableData] = useState<AvaliableSynchronizationTableDataItem[]>([]);
  const [preprocessTableData, setPreprocessTableData] = useState<
    AvaliableSynchronizationTableDataItem[]
  >([]);
  const dispatch = useTemuNotPersisAvaliableSynchronizationStore((state) => state.dispatch);
  const [currentTotal, setCurrentTotal] = useState(0);
  const localStorageKey = config.temu.temuAvaliableSynchronization;
  const [isRunning, setIsRunning] = useState(false);
  const { filterString, setFilterString, filteredTableDate } =
    useFilterTable<AvaliableSynchronizationTableDataItem>(tableData, [
      'skuInfo',
      'productId',
      'skcId',
      'skuId',
      'opeartionResult',
    ]);
  const deferredTableData = useDeferredValue(filteredTableDate);

  const id = useId();

  // console.log(currentTotal);

  const [storedValue, setStoredValue] = useLocalStorage<LocalStoredValue>(localStorageKey, {
    mallId: 0,
    siteId: 100,
    status: 100,
    fetchPageSize: 200,
    synchronizationToZeroCondition: {
      minGigaAvaliable: 5,
      minAndEqualRateOfMargin: 12,
    },
  });
  const [malInfoList, setMalInfoList] = useState<malInfo[]>([]);

  const { saveMallTableData, getMallTableData, persistedMallTableData, clearMallTableData } =
    useSaveTableData<AvaliableSynchronizationTableDataItem>({
      storageKey: config.temu.temuAvaliableSynchronizationMallTableData,
    });

  // 当店铺切换时修改 tableData
  useEffect(() => {
    const tableData = getMallTableData(generateMallTableDataKey(storedValue));
    if (tableData) {
      setTableData(tableData);
      setCurrentTotal(tableData.length);
      setPreprocessTableData(tableData);
    } else {
      setTableData([]);
      setCurrentTotal(0);
      setPreprocessTableData([]);
    }
    // console.log('tableData', mallTableData);
  }, [storedValue]);

  // 获取店铺列表信息
  useEffect(() => {
    async function getMallInfoList() {
      try {
        const result = await getTemuUserInfo();
        if (result.success) {
          const { companyList } = result.result;
          const malInfoList = companyList.flatMap((item) => item.malInfoList);
          // console.log(malInfoList);
          setMalInfoList(malInfoList);
          if (malInfoList.length > 0) {
            setStoredValue((prev) => {
              return {
                ...prev,
                mallId: malInfoList[0].mallId,
              };
            });
          }
        } else {
          throw new Error(result.errorMsg || '');
        }
      } catch (error) {
        // console.log(error)
        toast.error(`获取店铺列表失败: ${(error as Error).message}`);
      }
    }
    getMallInfoList();
  }, []);

  const updateTableData = useCallback(
    (tableDataItem: AvaliableSynchronizationTableDataItem) => {
      tableDataItem.timeStamp = new Date().getTime();
      // 如果 productId 已经存在于 tableData 中,那么就更新它,否则就添加一个新的
      setTableData((prev) => {
        const index = prev.findIndex((item) => item.productId === tableDataItem.productId);
        let newTableData = [];
        if (index === -1) {
          newTableData = [...prev, tableDataItem];
        } else {
          // console.log('更新表格数据', tableDataItem);
          newTableData = [...prev.slice(0, index), tableDataItem, ...prev.slice(index + 1)];
        }
        saveMallTableData(generateMallTableDataKey(storedValue), newTableData);
        return newTableData;
      });
    },
    [storedValue],
  );

  const runTask = useCallback(
    async (
      tableDataItem: AvaliableSynchronizationTableDataItem,
      options: RunTaskOptions = {} as RunTaskOptions,
    ) => {
      const { skuInfo, temuStock, temuPrice, skcId, skcInfo, skuId, mallId, timeStamp, productId } =
        tableDataItem;

      const { forceGigaAvaliable } = options;

      const minGigaAvaliable = storedValue.synchronizationToZeroCondition.minGigaAvaliable;
      const minAndEqualRateOfMargin =
        storedValue.synchronizationToZeroCondition.minAndEqualRateOfMargin;
      if (!skuInfo || Number.isNaN(temuStock) || Number.isNaN(temuPrice)) {
        tableDataItem.opeartionResult = '失败(无法获取到 temu 产品的 sku 信息)';
        updateTableData(tableDataItem);
        toast.error(`${productId} 无法获取到 temu 产品的 sku 信息`, {
          position: 'top-right',
        });
        throw new Error(`${productId} 无法获取到 temu 产品的 sku 信息`);
      }

      let gigaAvaliable = NaN;
      // giga 商品价格,单位是美分,如果不能获取返回 0
      let gigaPrice = NaN;

      // 如果有强制库存存在,那么就不再去获取 giga 商品库存了
      if (forceGigaAvaliable !== undefined) {
        gigaAvaliable = forceGigaAvaliable;
      } else {
        const [gigaSku, gigaProductId] = getGigaSkuAndProductId(skuInfo);
        try {
          const [priceResult, baseInfoResult] = await Promise.all([
            getProductPrice(gigaProductId),
            getGigaProductBaseInfo(gigaProductId),
          ]);
          if (priceResult.code === 200) {
            if (!priceResult.data.qty_visible) {
              throw new Error(`请先登录 giga 网站`);
            }
            gigaAvaliable = priceResult.data?.quantity?.quantity || 0;
            gigaPrice = getProductTotalPrice(priceResult);
            // 如果是 -1000 * 100 那么表示无法获取基础价格
            if (gigaPrice === 0 || gigaPrice === config.NotFoundBaseGigaProductPrice * 100) {
              // throw new Error(`giga 商品价格为 0,请检查商品是否存在`);
              // 如果价格为 0,表明商品是不可用的,这个时候把库存设置为 0
              gigaAvaliable = 0;
            }
          } else {
            throw new Error(`${priceResult && priceResult.msg}`);
          }

          // 添加禁售的平台
          const { non_sellable_platform } = baseInfoResult;
          tableDataItem.non_sellable_platform = non_sellable_platform;

          // 如果是 temu 禁售的商品,那么把库存设置为 0
          if (non_sellable_platform.includes('temu')) {
            gigaAvaliable = 0;
          }
        } catch (error) {
          toast.error(`${skuInfo} 获取 giga 库存和价格失败: ${(error as Error).message}`, {
            position: 'top-right',
          });
          tableDataItem.opeartionResult = '失败(获取 giga 库存和价格失败)';
          updateTableData(tableDataItem);
          throw error;
        }
        // console.log(gigaAvaliable, gigaPrice);
      }

      tableDataItem.gigaPrice = gigaPrice;
      tableDataItem.gigaAvaliable = gigaAvaliable;
      // 毛利率的计算是：(gigaAvaliable - gigaPrice) / gigaPrice * 100
      tableDataItem.rateOfMargin = ((temuPrice - gigaPrice) / gigaPrice) * 100;

      // 更新操作 nextStock 是要更新的库存
      let nextStock = gigaAvaliable;
      // 如果库存不满足条件,就设置为 0
      if (
        gigaAvaliable < minGigaAvaliable ||
        tableDataItem.rateOfMargin <= minAndEqualRateOfMargin
      ) {
        nextStock = 0;
      }

      // 如果两者库存一样,那么就不用同步
      if (nextStock === temuStock) {
        tableDataItem.nextStock = nextStock;
        tableDataItem.opeartionResult = `成功(更新前后库存一样,无需同步)`;
        updateTableData(tableDataItem);
        return;
      }

      try {
        // 获取 warehouseId
        const queryBtgProductStockInfoResult = await queryBtgProductStockInfo({
          productId: productId,
          productSkuId: skuId,
          mallId: mallId,
        });

        let warehouseId = '';
        if (queryBtgProductStockInfoResult.success) {
          warehouseId =
            queryBtgProductStockInfoResult.result.productStockList[0]?.warehouseStockList[0]
              ?.warehouseInfo.warehouseId || '';
          if (warehouseId === '') {
            throw new Error(`获取云仓 id 失败`);
          }
        } else {
          throw new Error(`获取云仓 id 失败`);
        }
        // 更新库存
        const updateMmsBtgProductSalesStockResult = await updateMmsBtgProductSalesStock({
          productId: productId,
          productSkuId: skuId,
          mallId: mallId,
          currentStockAvailable: temuStock,
          stockDiff: nextStock - temuStock,
          warehouseId: warehouseId,
        });
        if (updateMmsBtgProductSalesStockResult.success) {
          tableDataItem.opeartionResult = '成功(库存同步完成)';
          tableDataItem.nextStock = nextStock;
          updateTableData(tableDataItem);
          return;
        } else {
          throw new Error(updateMmsBtgProductSalesStockResult.errorMsg || '更新库存失败');
        }
      } catch (error) {
        // console.log(tableDataItem);
        toast.error(`${productId} 更新库存失败: ${(error as Error).message}`, {
          position: 'top-right',
        });
        tableDataItem.opeartionResult = `失败(${(error as Error).message})`;
        updateTableData(tableDataItem);
        throw error;
      }
    },
    [updateTableData, storedValue],
  );

  const runBatchTask = useCallback(
    async (
      preprocessTableData: AvaliableSynchronizationTableDataItem[],
      isEnterQueue = true,
      runTaskOptions?: RunTaskOptions,
    ) => {
      await Promise.all(
        preprocessTableData.map((preprocessTableDataItem) => {
          if (isEnterQueue) {
            return new Promise((resolve, reject) => {
              dispatch({
                type: 'enqueueTask',
                resolve,
                reject,
                task: {
                  handleTask: async () => {
                    await runTask(preprocessTableDataItem, runTaskOptions);
                  },
                  taskInfo: {
                    id: preprocessTableDataItem.productId,
                    ...preprocessTableDataItem,
                  },
                },
              });
            });
          } else {
            return runTask(preprocessTableDataItem, runTaskOptions);
          }
        }),
      );
    },
    [runTask],
  );

  async function fetchAndSynchronizationAvaliable() {
    const preprocessTableData = await fetchTemuProductInfo({
      isSavePreprocessTableData: false,
    });
    await runBatchTask(preprocessTableData);
  }

  async function fetchTemuProductInfo({
    isSavePreprocessTableData,
  }: {
    isSavePreprocessTableData: boolean;
  }) {
    setIsRunning(true);
    setTableData([]);
    setCurrentTotal(0);
    const pageSize = storedValue.fetchPageSize || 200;

    // 获取所有的 temu 产品信息
    const temuTotalProduct = await getTemuTotalProductByMallId({
      mallId: storedValue.mallId,
      pageSize,
      status: storedValue.status,
      obtainedTotalPageSize: (totalSize) => {
        setCurrentTotal(totalSize);
      },
    });

    setIsRunning(false);

    const preprocessTableData = temuTotalProduct.map((temuProduct) => {
      const { skuInfo, temuStock, temuPrice, productId, skcId, skcInfo, skuId } = temuProduct;
      return {
        skuInfo: skuInfo,
        temuStock: temuStock,
        nextStock: NaN,
        gigaPrice: NaN,
        temuPrice: temuPrice,
        rateOfMargin: NaN,
        productId: productId,
        skcId: skcId,
        skcInfo: skcInfo,
        skuId: skuId,
        mallId: storedValue.mallId || NaN,
        productCreateAt: temuProduct.productCreateAt,
        timeStamp: Date.now(),
        opeartionResult: '还未同步',
        gigaAvaliable: NaN,
        non_sellable_platform: [],
      };
    });
    // console.log(preprocessTableData);
    setTableData(preprocessTableData);
    saveMallTableData(generateMallTableDataKey(storedValue), preprocessTableData);
    // 如果是有后续的上报活动,那么不用设置预配置信息
    if (!isSavePreprocessTableData) {
      return preprocessTableData;
    }
    setPreprocessTableData(preprocessTableData);
    return preprocessTableData;
  }

  async function synchronizationAvaliable() {
    await runBatchTask(preprocessTableData);
  }

  async function clearTableData() {
    setTableData([]);
    setPreprocessTableData([]);
    saveMallTableData(generateMallTableDataKey(storedValue), []);
    persistedMallTableData();
  }

  return (
    <div {...props} className={cn(className, 'flex flex-col')}>
      <div className="flex items-center">
        <div className="flex gap-2 items-center mr-3">
          <Label className="whitespace-nowrap mb-0" htmlFor={id + 'mall-info-list'}>
            店铺账号:
          </Label>
          <Select
            value={storedValue.mallId + ''}
            onValueChange={(value) => {
              // console.log(value);
              setStoredValue((prev) => {
                return {
                  ...prev,
                  mallId: +value,
                };
              });
            }}
          >
            <SelectTrigger id={id + 'mall-info-list'} className="w-[120px]">
              <SelectValue placeholder="---- 请选择店铺 ----" />
            </SelectTrigger>
            <SelectContent
              style={{
                zIndex: config.SelectZindex,
              }}
            >
              <SelectGroup>
                {malInfoList.map(({ mallId, mallName }) => {
                  return (
                    <SelectItem key={mallId} value={mallId + ''}>
                      {mallName}
                    </SelectItem>
                  );
                })}
              </SelectGroup>
            </SelectContent>
          </Select>
        </div>
        <div className="flex gap-2 items-center mr-3">
          <Label className="whitespace-nowrap mb-0" htmlFor={id + 'site-info-list'}>
            站点:
          </Label>
          <Select
            value={storedValue.siteId + ''}
            onValueChange={(value) => {
              // console.log(value);
              setStoredValue((prev) => {
                return {
                  ...prev,
                  siteId: +value,
                };
              });
            }}
          >
            <SelectTrigger id={id + 'site-info-list'} className="w-[120px]">
              <SelectValue placeholder="---- 请选择站点 ----" />
            </SelectTrigger>
            <SelectContent
              style={{
                zIndex: config.SelectZindex,
              }}
            >
              <SelectGroup>
                {siteList.map(({ siteId, siteName }) => {
                  return (
                    <SelectItem key={siteId} value={siteId + ''}>
                      {siteName}
                    </SelectItem>
                  );
                })}
              </SelectGroup>
            </SelectContent>
          </Select>
        </div>
        <div className="flex gap-2 items-center">
          <Label className="whitespace-nowrap mb-0" htmlFor={id + '-status'}>
            产品状态:
          </Label>
          <Select
            value={storedValue.status + ''}
            onValueChange={(value) => {
              // console.log(value);
              setStoredValue((prev) => {
                return {
                  ...prev,
                  status: +value,
                };
              });
            }}
          >
            <SelectTrigger id={id + '-status'} className="w-[120px]">
              <SelectValue placeholder="---- 请选择产品状态 ----" />
            </SelectTrigger>
            <SelectContent
              style={{
                zIndex: config.SelectZindex,
              }}
            >
              <SelectGroup>
                {skcTopStatusList.map(({ label, status }) => {
                  return (
                    <SelectItem key={status} value={status + ''}>
                      {label}
                    </SelectItem>
                  );
                })}
              </SelectGroup>
            </SelectContent>
          </Select>
        </div>
        <div className="flex px-3 gap-2 items-center py-4">
          <Label className="whitespace-nowrap" htmlFor={id + '-fetch-page-size'}>
            一次拉取商品数量:
          </Label>
          <Input
            type="number"
            value={storedValue.fetchPageSize}
            onChange={(event) => {
              const newFetchPageSize = Number(event.target.value);
              if (newFetchPageSize > 1000 || newFetchPageSize < 1) {
                toast.error('每次拉取商品数量必须在 1 到 1000 之间');
                return;
              }
              setStoredValue((prev) => {
                return {
                  ...prev,
                  fetchPageSize: newFetchPageSize,
                };
              });
            }}
            id={id + '-fetch-page-size'}
            className="h-10 rounded-md border border-input px-3 py-2 w-[120px]"
          />
        </div>
      </div>

      <div className="border border-input rounded-lg py-3 pb-0 pl-2 relative mt-1">
        <span className="absolute left-5 top-0 translate-y-[-50%] px-1 text-base bg-white">
          库存同步为 0 的条件
        </span>
        <div className="flex items-center">
          <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap" htmlFor={id + '-giga-avaliable'}>
              giga 库存数:
            </Label>
            <div className="relative">
              <div className="absolute w-[40px] bg-muted h-full flex items-center">
                <span className="m-auto text-sm">{'<'}</span>
              </div>
              <Input
                value={storedValue.synchronizationToZeroCondition.minGigaAvaliable}
                type="number"
                onChange={(event) => {
                  setStoredValue({
                    ...storedValue,
                    synchronizationToZeroCondition: {
                      ...storedValue.synchronizationToZeroCondition,
                      minGigaAvaliable: Number(event.target.value),
                    },
                  });
                }}
                id={id + '-giga-avaliable'}
                className="h-10 w-32 rounded-md border border-input px-3 py-2 mr-auto pl-[50px]"
              />
            </div>
          </div>
          <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap" htmlFor={id + '-rate-of-margin'}>
              毛利率:
            </Label>
            <div className="relative">
              <div className="absolute w-[40px] bg-muted h-full flex items-center">
                <span className="m-auto text-sm">{'≤'}</span>
              </div>
              <Input
                type="number"
                value={storedValue.synchronizationToZeroCondition.minAndEqualRateOfMargin}
                onChange={(event) => {
                  setStoredValue({
                    ...storedValue,
                    synchronizationToZeroCondition: {
                      ...storedValue.synchronizationToZeroCondition,
                      minAndEqualRateOfMargin: Number(event.target.value),
                    },
                  });
                }}
                id={id + '-rate-of-margin'}
                className="h-10 w-48 rounded-md border border-input px-3 py-2 mr-auto pl-[50px] pr-[50px]"
              />
              <div className="absolute w-[40px] bg-muted h-full flex items-center right-0 top-0">
                <span className="m-auto text-sm">{'%'}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="grow relative flex flex-col">
        <div className="mt-2 flex items-center">
          <Button
            onClick={async () => {
              try {
                await fetchTemuProductInfo({
                  isSavePreprocessTableData: true,
                });
                // 持久化一下数据
                persistedMallTableData();
                toast.success('获取商品完成');
              } catch (error) {
                toast.error((error as Error).message);
              }
            }}
            size="sm"
            className="primary-color mr-3"
          >
            获取商品
          </Button>
          <Button
            disabled={preprocessTableData.length === 0 ? true : false}
            onClick={async () => {
              await synchronizationAvaliable();
              // 持久化一下数据
              persistedMallTableData();
              toast.success('库存同步任务完成');
            }}
            size="sm"
            className="primary-color mr-3"
          >
            同步库存
          </Button>
          <Button
            onClick={async () => {
              try {
                await fetchAndSynchronizationAvaliable();
                // 持久化一下数据
                persistedMallTableData();
                toast.success('库存同步任务完成');
              } catch (error) {
                toast.error((error as Error).message);
              }
            }}
            size="sm"
            className="primary-color"
          >
            获取并同步
          </Button>
          <span className="ml-3">
            {isRunning ? '(获取商品总数中...)' : ''}
            {
              skcTopStatusList.find((skcTopStatus) => skcTopStatus.status === storedValue.status)
                ?.label
            }
            : {currentTotal} 个商品
          </span>
          <div className="flex px-3 gap-2 items-center py-4">
            <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
            <Input
              placeholder="货号/SPU/SKC/SKU/结果"
              value={filterString}
              onChange={(event) => {
                setFilterString(event.target.value);
              }}
              className={cn(
                'flex h-10 w-full bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50 rounded-md border border-input',
                className,
              )}
              {...props}
            />
          </div>
          <Button
            onClick={async () => {
              try {
                persistedMallTableData();
                toast.success('列表数据保存成功');
              } catch (error) {
                toast.error((error as Error).message);
              }
            }}
            size="sm"
            className="ml-auto mr-3"
          >
            保存列表
          </Button>
          <Button
            onClick={async () => {
              window.parent.postMessage(
                {
                  type: PostMessageType.exportCorssOriginData,
                  data: {
                    data: JSON.stringify({
                      tableData: tableData,
                    }),
                    suggestedName: `同步库存列表数据.json`,
                  },
                },
                'https://seller.kuajingmaihuo.com/',
              );
            }}
            size="sm"
            className="mr-3"
          >
            导出列表
          </Button>
          <Button
            onClick={async () => {
              window.parent.postMessage(
                {
                  type: PostMessageType.importCorssOriginData,
                },
                'https://seller.kuajingmaihuo.com/',
              );

              window.addEventListener(
                'message',
                async (message: MessageEvent<SendCorssOriginDataMessage>) => {
                  if (message.data.type === PostMessageType.sendCorssOriginData) {
                    const dataString = message.data.data.data;
                    // console.log(dataString);
                    try {
                      const tableData = JSON.parse(dataString).tableData;
                      if (!tableData) {
                        throw new Error('是否导入错数据信息');
                      }
                      setTableData(tableData);
                      toast.success(`成功导入配置`);
                    } catch (error) {
                      toast.error(`导入配置失败 ${(error as Error).message}`);
                    }
                  }
                },
                {
                  once: true,
                },
              );
            }}
            size="sm"
            className="mr-3"
          >
            导入列表
          </Button>
          <Button
            onClick={async () => {
              setTableData([]);
              setPreprocessTableData([]);
              clearMallTableData();
              toast.success('清空保存数据成功');
            }}
            variant={'destructive'}
            size="sm"
            className="mr-3"
          >
            清空保存数据
          </Button>
          <Button
            onClick={async () => {
              clearTableData();
            }}
            variant={'destructive'}
            size="sm"
            className=""
          >
            清空列表
          </Button>
        </div>
        <TemuProductTable
          mallId={storedValue.mallId}
          data={deferredTableData}
          runBatchTask={runBatchTask}
        ></TemuProductTable>
        <div className="mt-auto" id="avaliable-synchronization-resume">
          <AvaliableSynchronizationOperation></AvaliableSynchronizationOperation>
          {/* <AvaliableSynchronizationResume
            resumeInfo={(resumeInfoData) => {
              console.log(resumeInfoData);
              const currentTotal = resumeInfoData.currentTotal;
              const tableData = resumeInfoData.tableData;
              setTableData(tableData || []);
              setCurrentTotal(currentTotal || 0);
            }}
            tableData={tableData}
            currentTotal={currentTotal}
            runBatchTask={runBatchTask}
            container="#avaliable-synchronization-resume"
          ></AvaliableSynchronizationResume> */}
        </div>
      </div>
    </div>
  );
}

export interface PageParams {
  pageSize: number;
}

const TemuProductTable = memo(function TemuProductTable({
  data,
  runBatchTask,
  mallId,
}: {
  data: AvaliableSynchronizationTableDataItem[];
  runBatchTask: (
    preprocessTableData: AvaliableSynchronizationTableDataItem[],
    isEnterQueue?: boolean,
    runBatchTask?: RunTaskOptions,
  ) => Promise<void>;
  mallId: number;
}) {
  const localStorageKey = config.temu.temuAvaliableSynchronizationTableKey;
  const id = useId();
  const [columnPinning, setColumnPinning] = useState<ColumnPinningState>({
    left: ['select', 'skuInfo', 'temuStock', 'nextStock'],
    right: ['opeartionResult', 'actions'],
  });
  const [storedValue, setStoredValue] = useLocalStorage<PageParams>(localStorageKey, {
    pageSize: 10,
  });

  const [pagination, setPagination] = useState<PaginationState>({
    pageIndex: 0,
    pageSize: storedValue.pageSize,
  });
  const [rowSelection, setRowSelection] = useState({});
  const [sorting, setSorting] = useState<SortingState>([]);
  const headerHeight = 60;
  const cellHeight = 50;

  const pageQueryByProductIds = useCallback(
    async (productIds: number[], runTaskOptions?: RunTaskOptions) => {
      const temuTotalProduct = await getTemuTotalProductByProductIds({
        mallId: mallId,
        productIds: productIds,
      });
      const preprocessTableData = temuTotalProduct.map((temuProduct) => {
        const { skuInfo, temuStock, temuPrice, productId, skcId, skcInfo, skuId, productCreateAt } =
          temuProduct;
        return {
          skuInfo: skuInfo,
          temuStock: temuStock,
          nextStock: NaN,
          gigaPrice: NaN,
          temuPrice: temuPrice,
          rateOfMargin: NaN,
          productId: productId,
          skcId: skcId,
          skcInfo: skcInfo,
          skuId: skuId,
          mallId: mallId || NaN,
          productCreateAt: productCreateAt,
          timeStamp: Date.now(),
          opeartionResult: '还未同步',
          gigaAvaliable: NaN,
          non_sellable_platform: [],
        };
      });
      await runBatchTask(preprocessTableData, false, runTaskOptions);
    },

    [mallId, runBatchTask],
  );

  const columns: ColumnDef<AvaliableSynchronizationTableDataItem>[] = useMemo(() => {
    const columns: ColumnDef<AvaliableSynchronizationTableDataItem>[] = [];
    columns.push({
      id: 'select',
      header: ({ table }) => (
        <Checkbox
          checked={
            table.getIsAllPageRowsSelected() ||
            (table.getIsSomePageRowsSelected() && 'indeterminate')
          }
          onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
          aria-label="Select all"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(value) => row.toggleSelected(!!value)}
          aria-label="Select row"
        />
      ),
      enableSorting: false,
      enableHiding: false,
    });
    columns.push({
      id: 'skuInfo',
      accessorKey: 'skuInfo',
      header: () => <div className="text-center whitespace-nowrap">sku货号</div>,
      cell: ({ row }) => {
        const skuInfo: string = row.getValue('skuInfo');
        return (
          <div
            onClick={() => {
              gotoGigaProductPage(skuInfo);
            }}
            className="text-left whitespace-nowrap cursor-pointer text-blue-600 underline"
          >
            {skuInfo}
          </div>
        );
      },
    });
    columns.push({
      id: 'temuStock',
      accessorKey: 'temuStock',
      header: () => <div className="text-center whitespace-nowrap">同步前库存</div>,
      cell: ({ row }) => {
        const temuStock: number = row.getValue('temuStock');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(temuStock) ? 'NaN' : temuStock}
          </div>
        );
      },
    });
    columns.push({
      id: 'nextStock',
      accessorKey: 'nextStock',
      header: () => <div className="text-center whitespace-nowrap">同步后库存</div>,
      cell: ({ row }) => {
        const nextStock: number = row.getValue('nextStock');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(nextStock) ? 'NaN' : nextStock}
          </div>
        );
      },
    });
    columns.push({
      id: 'productId',
      accessorKey: 'productId',
      header: () => <div className="text-center whitespace-nowrap">SPUID</div>,
      cell: ({ row }) => {
        const productId: number = row.getValue('productId');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(productId) ? 'NaN' : productId}
          </div>
        );
      },
    });
    columns.push({
      id: 'temuPrice',
      accessorKey: 'temuPrice',
      header: () => <div className="text-center whitespace-nowrap">店铺价格</div>,
      cell: ({ row }) => {
        const temuPrice: number = row.getValue('temuPrice');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(temuPrice) ? 'NaN' : +temuPrice / 100}
          </div>
        );
      },
    });
    columns.push({
      id: 'gigaPrice',
      accessorKey: 'gigaPrice',
      header: () => <div className="text-center whitespace-nowrap">giga价格</div>,
      cell: ({ row }) => {
        const gigaPrice: number = row.getValue('gigaPrice');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(gigaPrice) ? 'NaN' : +gigaPrice / 100}
          </div>
        );
      },
    });
    columns.push({
      id: 'rateOfMargin',
      accessorKey: 'rateOfMargin',
      header: () => <div className="text-center whitespace-nowrap">毛利率(%)</div>,
      cell: ({ row }) => {
        const rateOfMargin: number = row.getValue('rateOfMargin');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(rateOfMargin) ? 'NaN' : (+rateOfMargin).toFixed(2)}
          </div>
        );
      },
    });
    columns.push({
      id: 'gigaAvaliable',
      accessorKey: 'gigaAvaliable',
      header: () => <div className="text-center whitespace-nowrap">giga库存</div>,
      cell: ({ row }) => {
        const gigaAvaliable: number = row.getValue('gigaAvaliable');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(gigaAvaliable) ? 'NaN' : gigaAvaliable}
          </div>
        );
      },
    });
    // opeartionResult: string;
    columns.push({
      id: 'skcId',
      accessorKey: 'skcId',
      header: () => <div className="text-center whitespace-nowrap">SKCID</div>,
      cell: ({ row }) => {
        const skcId: number = row.getValue('skcId');
        return (
          <div className="text-left whitespace-nowrap">{Number.isNaN(skcId) ? 'NaN' : skcId}</div>
        );
      },
    });

    columns.push({
      id: 'non_sellable_temu',
      accessorFn(tableItem) {
        const non_sellable_platform: string[] = tableItem.non_sellable_platform || [];
        return non_sellable_platform.includes('temu');
      },
      header: () => <div className="text-center whitespace-nowrap">禁售Temu</div>,
      cell: ({ row }) => {
        const non_sellable_platform: string[] = row.original.non_sellable_platform || [];
        return (
          <div className="text-left whitespace-nowrap">
            {non_sellable_platform.includes('temu') ? '是' : '否'}
          </div>
        );
      },
    });

    columns.push({
      id: 'skcInfo',
      accessorKey: 'skcInfo',
      header: () => <div className="text-center whitespace-nowrap">skc货号</div>,
      cell: ({ row }) => {
        const skcInfo: string = row.getValue('skcInfo');
        return <div className="text-left whitespace-nowrap">{skcInfo}</div>;
      },
    });
    columns.push({
      id: 'skuId',
      accessorKey: 'skuId',
      header: () => <div className="text-center whitespace-nowrap">skuId</div>,
      cell: ({ row }) => {
        const skuId: string = row.getValue('skuId');
        return (
          <div className="text-left whitespace-nowrap">{Number.isNaN(skuId) ? 'NaN' : skuId}</div>
        );
      },
    });
    columns.push({
      id: 'mallId',
      accessorKey: 'mallId',
      header: () => <div className="text-center whitespace-nowrap">店铺ID</div>,
      cell: ({ row }) => {
        const mallId: number = row.getValue('mallId');
        return (
          <div className="text-left whitespace-nowrap">{Number.isNaN(mallId) ? 'NaN' : mallId}</div>
        );
      },
    });
    columns.push({
      id: 'productCreateAt',
      accessorKey: 'productCreateAt',
      header: () => <div className="text-center whitespace-nowrap">创建时间</div>,
      cell: ({ row }) => {
        const productCreateAt: number = row.getValue('productCreateAt');
        return (
          <div className="text-left whitespace-nowrap">
            {new Date(productCreateAt).toLocaleString()}
          </div>
        );
      },
    });
    columns.push({
      id: 'timeStamp',
      accessorKey: 'timeStamp',
      header: () => <div className="text-center whitespace-nowrap">处理时间</div>,
      cell: ({ row }) => {
        const timeStamp: number = row.getValue('timeStamp');
        return (
          <div className="text-left whitespace-nowrap">{new Date(timeStamp).toLocaleString()}</div>
        );
      },
    });
    columns.push({
      id: 'opeartionResult',
      accessorKey: 'opeartionResult',
      header: () => <div className="text-center whitespace-nowrap">操作结果</div>,
      cell: ({ row }) => {
        const opeartionResult: string = row.getValue('opeartionResult');
        return (
          <div
            title={opeartionResult}
            className={`text-left max-w-20 whitespace-nowrap overflow-hidden text-ellipsis`}
            style={{
              color: getOperationResultColor(opeartionResult),
            }}
          >
            {opeartionResult}
          </div>
        );
      },
    });

    columns.push({
      id: 'actions',
      enableHiding: false,
      enableSorting: false,
      header() {
        return <div className="text-center">操作</div>;
      },
      cell: ({ row }) => {
        return (
          <div>
            <Button
              onClick={async () => {
                const productId: number = row.getValue('productId');
                toast.promise(pageQueryByProductIds([productId]), {
                  loading: `正在同步 [${productId}] 的库存...`,
                  success: (result) => {
                    return `同步 [${productId}] 的库存成功`;
                  },
                  error: (error) => {
                    return `同步 [${productId}] 的库存失败: ${(error as Error).message}`;
                  },
                });
              }}
              size="sm"
              className="hover:bg-[#337AB7] bg-[#428BCA]"
            >
              库存同步
            </Button>
          </div>
        );
      },
    });
    return columns;
  }, [pageQueryByProductIds]);

  const table = useReactTable({
    data,
    columns,
    onColumnPinningChange: setColumnPinning,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    onPaginationChange: setPagination,
    onRowSelectionChange: setRowSelection,
    onSortingChange: setSorting,
    state: {
      rowSelection,
      columnPinning,
      pagination,
      sorting,
    },
  });

  return (
    data.length > 0 && (
      <div className="w-full grow relative flex flex-col mt-2">
        <div className="grow relative">
          <div className="rounded-sm !absolute h-full w-full overflow-auto">
            <div className="rounded-md border min-w-full inline-flex [&_thead]:sticky [&_thead]:top-[1px] [&_thead]:[box-shadow:0px_0px_0px_1px_#cfcfcf] [&_thead]:bg-[#f5f5f5]  [&_table]:!overflow-visible">
              <div className="sticky left-[0px] z-10 bg-white">
                <Table className="[&_td]:border [&_td]:border-input [&_th]:border [&_th]:border-input text-xs">
                  <TableHeader>
                    {table.getLeftHeaderGroups().map((headerGroup) => (
                      <TableRow key={headerGroup.id}>
                        {headerGroup.headers.map((header) => {
                          return (
                            <TableHead
                              key={header.id}
                              className="!p-2 relative"
                              style={{
                                height: headerHeight,
                              }}
                            >
                              {header.column.getCanSort() ? (
                                <div
                                  onClick={header.column.getToggleSortingHandler()}
                                  className="absolute cursor-pointer right-1 bottom-1"
                                  title={
                                    header.column.getCanSort()
                                      ? header.column.getNextSortingOrder() === 'asc'
                                        ? '升序'
                                        : header.column.getNextSortingOrder() === 'desc'
                                          ? '降序'
                                          : '默认排序'
                                      : undefined
                                  }
                                >
                                  <ArrowUpDown size={12}></ArrowUpDown>
                                </div>
                              ) : null}
                              {header.isPlaceholder
                                ? null
                                : flexRender(header.column.columnDef.header, header.getContext())}
                            </TableHead>
                          );
                        })}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {table.getRowModel().rows?.length ? (
                      table.getRowModel().rows?.map((row) => {
                        return (
                          <TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>
                            {row.getLeftVisibleCells().map((cell) => (
                              <TableCell
                                key={cell.id}
                                className=""
                                style={{
                                  height: cellHeight,
                                }}
                              >
                                {flexRender(cell.column.columnDef.cell, cell.getContext())}
                              </TableCell>
                            ))}
                          </TableRow>
                        );
                      })
                    ) : (
                      <TableRow>
                        <TableCell colSpan={columns.length} className="h-24 text-center">
                          No results.
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
              <div className="relative grow">
                <Table className="text-xs [&_td]:border [&_td]:border-input [&_th]:border [&_th]:border-input">
                  <TableHeader>
                    {table.getCenterHeaderGroups().map((headerGroup) => (
                      <TableRow key={headerGroup.id}>
                        {headerGroup.headers.map((header) => {
                          return (
                            <TableHead
                              key={header.id}
                              className="!p-2 relative"
                              style={{
                                height: headerHeight,
                              }}
                            >
                              {header.column.getCanSort() ? (
                                <div
                                  onClick={header.column.getToggleSortingHandler()}
                                  className="absolute cursor-pointer right-1 bottom-1"
                                  title={
                                    header.column.getCanSort()
                                      ? header.column.getNextSortingOrder() === 'asc'
                                        ? '升序'
                                        : header.column.getNextSortingOrder() === 'desc'
                                          ? '降序'
                                          : '默认排序'
                                      : undefined
                                  }
                                >
                                  <ArrowUpDown size={12}></ArrowUpDown>
                                </div>
                              ) : null}
                              <div className="text-xs">
                                {header.isPlaceholder
                                  ? null
                                  : flexRender(header.column.columnDef.header, header.getContext())}
                              </div>
                            </TableHead>
                          );
                        })}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {table.getRowModel().rows?.length ? (
                      table.getRowModel().rows.map((row) => (
                        <TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>
                          {row.getCenterVisibleCells().map((cell) => (
                            <TableCell
                              key={cell.id}
                              className=""
                              style={{
                                height: cellHeight + 'px',
                              }}
                            >
                              {flexRender(cell.column.columnDef.cell, cell.getContext())}
                            </TableCell>
                          ))}
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell colSpan={columns.length} className="h-24 text-center">
                          No results.
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
              <div className="bg-white sticky right-0">
                <Table className="text-xs [&_td]:border [&_td]:border-input [&_th]:border [&_th]:border-input">
                  <TableHeader>
                    {table.getRightHeaderGroups().map((headerGroup) => (
                      <TableRow key={headerGroup.id}>
                        {headerGroup.headers.map((header) => {
                          return (
                            <TableHead
                              key={header.id}
                              className="!p-2 relative"
                              style={{
                                height: headerHeight,
                              }}
                            >
                              {header.column.getCanSort() ? (
                                <div
                                  onClick={header.column.getToggleSortingHandler()}
                                  className="absolute cursor-pointer right-1 bottom-1"
                                  title={
                                    header.column.getCanSort()
                                      ? header.column.getNextSortingOrder() === 'asc'
                                        ? '升序'
                                        : header.column.getNextSortingOrder() === 'desc'
                                          ? '降序'
                                          : '默认排序'
                                      : undefined
                                  }
                                >
                                  <ArrowUpDown size={12}></ArrowUpDown>
                                </div>
                              ) : null}
                              {header.isPlaceholder
                                ? null
                                : flexRender(header.column.columnDef.header, header.getContext())}
                            </TableHead>
                          );
                        })}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {table.getRowModel().rows?.length ? (
                      table.getRowModel().rows.map((row) => (
                        <TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>
                          {row.getRightVisibleCells().map((cell) => (
                            <TableCell
                              key={cell.id}
                              className=""
                              style={{
                                height: cellHeight + 'px',
                              }}
                            >
                              {flexRender(cell.column.columnDef.cell, cell.getContext())}
                            </TableCell>
                          ))}
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell colSpan={columns.length} className="h-24 text-center">
                          No results.
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </div>
          </div>
        </div>
        <div className="mt-1 relative">
          <div className="absolute">
            <Button
              onClick={async () => {
                if (table.getIsSomeRowsSelected() || table.getIsAllRowsSelected()) {
                  const productIds: number[] = table.getSelectedRowModel().rows.map((row) => {
                    const productId: number = row.getValue('productId');
                    return productId;
                  });
                  console.log(productIds);
                  toast.promise(pageQueryByProductIds(productIds), {
                    loading: '正在批量获取库存...',
                    success: (result) => {
                      return `批量获取库存成功`;
                    },
                    error: (error) => {
                      return `批量获取库存失败: ${(error as Error).message}`;
                    },
                  });
                }
              }}
              size="sm"
              className="hover:bg-[#337AB7] bg-[#428BCA] mr-3 mt-5"
            >
              批量同步库存
            </Button>

            <Button
              onClick={async () => {
                if (table.getIsSomeRowsSelected() || table.getIsAllRowsSelected()) {
                  const productIds: number[] = table.getSelectedRowModel().rows.map((row) => {
                    const productId: number = row.getValue('productId');
                    return productId;
                  });
                  // console.log(productIds);
                  toast.promise(
                    pageQueryByProductIds(productIds, {
                      forceGigaAvaliable: 0,
                    }),
                    {
                      loading: '正在批量获取库存...',
                      success: (result) => {
                        return `批量获取库存成功`;
                      },
                      error: (error) => {
                        return `批量获取库存失败: ${(error as Error).message}`;
                      },
                    },
                  );
                }
              }}
              size="sm"
              className="hover:bg-[#337AB7] bg-[#428BCA] mr-3 mt-5"
            >
              批量同步库存为 0
            </Button>
          </div>
          <TablePagination<AvaliableSynchronizationTableDataItem, PageParams>
            setStoredValue={setStoredValue}
            storedValue={storedValue}
            table={table}
            setPagination={setPagination}
          ></TablePagination>
        </div>
      </div>
    )
  );
});
